package com.wang.back.interceptor;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.wang.common.util.ConstatFinalUtil;
import com.wang.common.util.RedisUtil;
import com.wang.common.web.controller.BaseController;
import com.wang.users.pojo.AtRbacAdmins;
import com.wang.users.service.AtRbacAdminsService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 过滤器===保安
 * /back/AdminsBack/main
 * @author Tm
 */
@Component
@Log4j2
public class TicketInterceptor extends BaseController implements HandlerInterceptor{
    @Autowired
    private AtRbacAdminsService adminsService;

    /**
     * 保安要干的事情;
     * 通过==放行
     * 不通过==拦截
     *
     * chain:过滤器链
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.info("==TicketInterceptor(执行中)==:");
        /* 获取session */
        HttpSession session = request.getSession();
        /* 获取对象,此对象是登录的时候放进去;
         * 如果有,说明登录了.(买票)
         * 如果没有,说明没有登录,(没有买票,去买票)
         *  */
        AtRbacAdmins admins = (AtRbacAdmins) session.getAttribute("adminsSess");
        if (admins != null) {
            return true;
        } else {
            String resultJsonStr = (String) this.redisUtil.hashGet(RedisUtil.REDIS_KEY, ConstatFinalUtil.FINAL_CONFIG_ILL_LOGIN);
            JSONObject resultJson = JSON.parseObject(resultJsonStr);
            /* 必须买票 */
            String info = resultJson.getString(ConstatFinalUtil.FINAL_CONFIG_VALSTR);
            session.setAttribute("info", info);
            String loginUrl = request.getContextPath() + "/noLogin/adminsLogin";
            response.sendRedirect(loginUrl);
            return false;
        }
    }
}
